//
//  HMRefresshControl.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/13.
//  Copyright © 2015年 heima11. All rights reserved.
//

import UIKit
private let RefreshControlH: CGFloat = 50

//MARK : normal 正常状态  下拉状态 pulling Refreshing 刷新状态

enum HMrefresshState : Int {
    case Normal = 0
    case pulling = 1
    case Refreshing = 2

}



class HMRefresshControl: UIControl {

    var oldHmState: HMrefresshState = .Normal
    
    var HMstates : HMrefresshState = .Normal {
    
        didSet{
                switch HMstates
                {
            
                case .pulling:
                    
                    print("显示刷新 箭头调转方向")
                    messageLable.text = "放开飞起"
                    UIView.animateWithDuration(0.2, animations: { () -> Void in
                    self.pullarrows.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                        })
                    
                case .Normal:
                    print("显示箭头,隐藏菊花转")
                    messageLable.text = "下拉起飞"
                    pullarrows.hidden = false
                    self.indicator.stopAnimating()
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.pullarrows.transform = CGAffineTransformIdentity
                    })
                    if oldHmState == .Refreshing
                    {
                        UIView.animateWithDuration(0.25, animations: { () -> Void in
                            var contenInset = self.scrollview?.contentInset
                            contenInset?.top-=RefreshControlH
                            self.scrollview?.contentInset=contenInset!
                        })
                    }
                case .Refreshing:
                    print("隐藏箭头,菊花显示")
                    messageLable.text = "正在飞起"
                    self.pullarrows.hidden = true
                    self.indicator.startAnimating()
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contenInset = self.scrollview?.contentInset
                        contenInset?.top+=RefreshControlH
                        self.scrollview?.contentInset=contenInset!
                    })
                    sendActionsForControlEvents(.ValueChanged)
                }
            oldHmState = HMstates
         }
    
    
    }
    
    var scrollview : UIScrollView?
    
    var pullarrows : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    var poparrows : UIImageView = UIImageView (image: UIImage(named: ""))
    
    var messageLable : UILabel = {
        
        let lable = UILabel(color: UIColor.blueColor(), font: 15)
        
        lable.text = "下拉飞起"
        return lable
    
    }()
     lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    func endload(){
    
        HMstates = .Normal
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI(){
        
        backgroundColor = UIColor.redColor()
    
        var frame = self.frame
        frame.size = CGSize(width: SCREENW, height: RefreshControlH)
        
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        addSubview(pullarrows)
        addSubview(messageLable)
        addSubview(indicator)
        pullarrows.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        messageLable.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(pullarrows)
            make.leading.equalTo(pullarrows.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(pullarrows)
        }
    }
    
    //MARK : 在控件加到某一个控件上的时候会调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if  let newscrll = newSuperview as? UIScrollView
        {
            newscrll.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            
            self.scrollview = newscrll
            
            var frame = self.frame
            frame.size.width = newscrll.frame.width
            self.frame = frame
        }
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = scrollview?.contentOffset.y
        
        //        printLog(contentOffsetY)
        let contentInsetTop = scrollview?.contentInset.top ?? 0
        //        printLog()
        // 临界值(当前控件是否完否显示的临界值)
        let conditionValue = -contentInsetTop-RefreshControlH
        
        if scrollview!.dragging {
            
            if  HMstates == .Normal && contentOffsetY < conditionValue {
                //printLog("进入松手就刷新状态")
                HMstates = .pulling
                //
                // 进入松手就刷的新状态
            }else if  HMstates == .pulling && contentOffsetY >= conditionValue{
                // 进入默认状态
                //printLog("进入默认状态")
                HMstates = .Normal
            }
        }else{
            // 改成 刷新中 的状态有两个条件 : 首先松手,当前状态是 .Pulling 状态
            // 用户松手的时候会执行
            if HMstates == .pulling {
                HMstates = .Refreshing
            }
        }
    }
    
    deinit{
        scrollview?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
  
    
}
